package cn.smbms.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import cn.smbms.pojo.User;

public class CheckLoginInterceptor implements HandlerInterceptor {
	private Logger log = Logger.getLogger(CheckLoginInterceptor.class);

	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		long start = (long) arg0.getAttribute("start");
		long end = System.nanoTime();
		log.debug("请求所花时间>>>>>" + (end - start) + "<<<<<");
	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
		log.debug("本次请求" + arg0.getServletPath() + ",返回值：" + arg3);

	}

	@Override
	public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception {
		long start = System.nanoTime();
		arg0.setAttribute("start", start);
		log.debug("请求地址：" + arg0.getServletPath() + ",拦截的对象：" + arg2);
		log.debug(">>>>登录验证拦截");
		User user = (User) arg0.getSession().getAttribute("USER");
		if (null == user) {
			arg1.sendRedirect(arg0.getContextPath() + "/401.jsp");
			return false;
		}
		return true;
	}

}
